package leetcode;

/**
 * Created by Ghost on 2014/12/16 0016.
 */
public class Spiral_Matrix_II {
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int m=0,p=-1;
        int j=-1;

        for(int i=1;i<=n*n;i++){
            m = j+1;
            for(j=p+1;j<n && matrix[m][j]==0;j++,i++)
                matrix[m][j]=i;
            p = j-1;
            for(j=m+1;j<n && matrix[j][p]==0;j++,i++)
                matrix[j][p]=i;
            m=j-1;
            for(j=p-1;j>=0 && matrix[m][j]==0;j--,i++)
                matrix[m][j]=i;
            p=j+1;
            for(j=m-1;j>=0 && matrix[j][p]==0;j--,i++)
                matrix[j][p]=i;
            i--;
        }

        return matrix;
    }

    public static void main(String[] args){
        Spiral_Matrix_II spiral_matrix_ii = new Spiral_Matrix_II();
        int n=10;
        int[][] matrix = spiral_matrix_ii.generateMatrix(n);
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++)
                System.out.print(" "+matrix[i][j]);
            System.out.println();
        }
    }
}
